<?php

class OP_GoogleReader
{
    private $_username;
    private $_password;
    private $_sid;
    private $_loginUrl = 'https://www.google.com/accounts/ClientLogin';
    private $_autoUrl = 'http://www.google.com/reader/atom/';
    private $_userAgent = 'Firefox/5.0';
    private $_cookie;

    public function __construct($username, $password)
    {
        $this->_username = $username;
        $this->_password = $password;
    }

    public function login()
    {
        $curl = curl_init();
        $datas = array(
        'Email' => $this->_username,
        'Passwd' => $this->_password,
        'service' => 'reader',
        'source' => $this->_userAgent,
        'continue' => 'http://www.google.com'
        );
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $datas);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_URL, $this->_loginUrl);
        $content = curl_exec($curl);
        curl_close($curl);

        return $content;
    }

    public function getSid()
    {
        if ($this->_sid === null) {
            $content = $this->login();
            $start = stripos($content, 'sid=') + 4;
            $length = stripos($content, 'lsid=') - 5;
            $this->_sid = substr($content, $start, $length);
        }
        return $this->_sid;
    }

    public function getCookie()
    {
        if (null === $this->_cookie) {
            $cookie = array(
            'name' => $this->getSid(),
            'domain' => '.google.com',
            'path' => '/',
            'expires' => 1600000000
            );
            $cookies = array();
            foreach ($cookie as $key=>$val) {
                $cookies[] = "{$key}=" . addslashes($val);
            }
            $this->_cookie = implode(';', $cookies);
        }

        return $this->_cookie;
    }

    public function getAtom()
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_USERAGENT, $this->_userAgent);
        curl_setopt($curl, CURLOPT_HTTPGET, true);
        curl_setopt($curl, CURLOPT_COOKIE, $this->getCookie());
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_URL, $this->_autoUrl);
        $content = curl_exec($curl);
        curl_close($curl);
        return $content;
    }
}